﻿
@{
    var isEmbed = Context?.Request?.Query["embed"].ToString() == "1";
    Layout = isEmbed ? null : "_Layout";
}

<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />
<script src="~/js/site.js"></script>
<script src="~/layui/layui.js"></script>
<script src="~/js.cookie.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>

<button type="button" class="layui-btn" onclick="addProcess()">工序添加</button>

<!-- 查询区域 -->
<div class="layui-row" style="margin: 15px 0;">
    <div class="layui-col-md3">
        <div class="layui-input-group">
            <input type="text" id="ProcessCode" placeholder="工序编号" class="layui-input">
        </div>
    </div>
    <div class="layui-col-md3">
        <div class="layui-input-group">
            <input type="text" id="ProcessName" placeholder="工序名称" class="layui-input">
        </div>
    </div>
    <div class="layui-col-md2">
        <button type="button" class="layui-btn" onclick="searchProcess()">
            <i class="layui-icon layui-icon-search"></i> 查询
        </button>
    </div>
</div>

<table class="layui-table">
    <thead>
        <tr>
            <th>工序编号</th>
            <th>工序名称</th>
            <th>分类</th>
            <th>负责人</th>
            <th>工序状态</th>
            <th>所属部门</th>
            <th>备注</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody id="tb"></tbody>
</table>
<div id="demo-laypage-all"></div>


<script>
    //加载事件
    $(function(){
     
    shows()
    })
    var PageIndex=1;
    var PageSize=5;
    var TotalCount=0;
    var TotalPages=0;
    
    //获取工序分类列表
    function shows(){
        var ProcessCode = $("#ProcessCode").val();
        var ProcessName = $("#ProcessName").val();
 
        $.ajax({
            url: 'http://localhost:5161/api/Process/ProcessDtoQuery?PageIndex='+PageIndex+'&PageSize='+PageSize,
            dataType:'json',
            data:{ProcessCode:ProcessCode,ProcessName:ProcessName},
            type:'get',
            contentType:'application/json',
            async:false,
            success:res=>{
                console.log(res);
                TotalCount=res.data.totalCount;
                TotalPages=res.data.totalPages;
                $("#tb").empty();
 
                $(res.data.list).each(function(){
                    // 展示用文案转换
                    var displayStatus = this.processStatus;
                    if(this.processStatus==0){
                        displayStatus="启用"
                    }else{
                        displayStatus="禁用"
                    }
                    
                    var displayDept = this.departId;
                    if(this.departId==1){
                        displayDept="生产部"
                    }else if(this.departId==2){
                        displayDept="质检部"
                    }else if(this.departId==3){
                        displayDept="技术部"
                    }
                    
                    $("#tb").append(`
                       <tr data-row='${JSON.stringify(this).replace(/'/g, "&apos;")}'>
                        <th>${this.processCode}</th>
                        <th>${this.processName}</th>
                        <th>${this.ptName}</th>
                        <th>${this.responsibilityName}</th>
                        <th>${displayStatus}</th>
                        <th>${displayDept}</th>
                        <th>${this.note || ''}</th>
                        <th>
                            <button class="layui-btn layui-btn-sm" onclick="editProcess(this)">编辑</button>
                            <button class="layui-btn layui-btn-danger layui-btn-sm" onclick="deleteProcess(this)">删除</button>
                        </th>
                       </tr>
                    `)
                })
                
                // 渲染分页
                renderPagination();
            }
        })
    }
    
    //分页
    function renderPagination(){
        layui.use(function(){
          var laypage = layui.laypage;
          // 完整显示
          laypage.render({
            elem: 'demo-laypage-all', // 元素 id
            count: TotalCount, // 数据总数
            limit:PageSize,
            curr: PageIndex,
            limits: [5, 10, 15, 20],
            layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'], // 功能布局
            jump: function(obj, first){
              if (!first) {
                PageIndex = obj.curr;
                PageSize = obj.limit;
                shows();
              }
            }
          });
        });
    }
    
    //删除工序 - 使用data属性方式获取行数据
    function deleteProcess(button) {
        try {
            // 获取按钮所在的行
            var $row = $(button).closest('tr');
            // 从行的data-row属性获取数据
            var rowData = JSON.parse($row.attr('data-row'));
            
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.confirm('确定要删除工序 "' + rowData.processName + '" 吗？', {
                    icon: 3,
                    title: '确认删除'
                }, function(index){
                    // 用户确认删除
                    layer.close(index);
                    
                    // 显示加载状态
                    var loadIndex = layer.load(1, {shade: [0.3, '#000']});
                    
                    // 组装删除请求数据 - 按接口要求，直接传递对象，不包装在request字段中
                    var deleteData = {
                        id: rowData.id,
                        processCode: rowData.processCode,
                        processName: rowData.processName,
                        processStatus: rowData.processStatus,
                        isImportent: rowData.isImportent,
                        ptId: rowData.ptId,
                        note: rowData.note,
                        responsibilityName: rowData.responsibilityName,
                        departId: rowData.departId,
                        ptCode: rowData.ptCode,
                        ptName: rowData.ptName,
                        isUpdOrDel: true  // true表示删除，false表示修改
                    };
                    
                    console.log('准备删除的数据:', deleteData);
                    
                    $.ajax({
                        url: 'http://localhost:5161/api/Process/ProcessEdit',
                        dataType: 'json',
                        type: 'post',
                        contentType: 'application/json',
                        data: JSON.stringify(deleteData),
                        success: function(res) {
                            layer.close(loadIndex);
                            if(res.code == 200) {
                                layer.msg('删除成功', {icon: 1, time: 1500});
                                // 刷新列表
                                shows();
                            } else {
                                layer.msg(res.message || '删除失败', {icon: 2, time: 3000});
                            }
                        },
                        error: function(xhr, status, error) {
                            layer.close(loadIndex);
                            console.error('删除失败:', error);
                            layer.msg('网络错误，请重试', {icon: 2, time: 3000});
                        }
                    });
                });
            });
        } catch (e) {
            console.error('解析行数据失败:', e);
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.msg('数据解析失败，请重试', {icon: 2, time: 2000});
            });
        }
    }
    
    //编辑工序 - 跳转到编辑页面
    function editProcess(button) {
        try {
            // 获取按钮所在的行
            var $row = $(button).closest('tr');
            // 从行的data-row属性获取数据
            var rowData = JSON.parse($row.attr('data-row'));
            
            // 将行数据编码后作为URL参数传递
            var encodedData = encodeURIComponent(JSON.stringify(rowData));
            window.location.href = '/Process/ProcessAdd?mode=edit&data=' + encodedData;
            
        } catch (e) {
            console.error('解析行数据失败:', e);
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.msg('数据解析失败，请重试', {icon: 2, time: 2000});
            });
        }
    }

    // 查询工序
    function searchProcess() {
        PageIndex = 1; // 重置到第一页
        shows();
    }

    // 绑定回车键事件
    $(document).ready(function() {
        $("#ProcessCode, #ProcessName").on('keypress', function(e) {
            if (e.which === 13) {
                searchProcess();
            }
        });
    });

    // 添加工序 - 跳转到添加页面
    function addProcess() {
        window.location.href = '/Process/ProcessAdd';
    }
</script>